package com.heima.search.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.dtos.UserSearchDto;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.search.service.HistorySearchService;
import com.heima.search.service.SearchService;
import com.heima.utils.thread.ApThreadLocalUtil;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightField;
import org.elasticsearch.search.sort.SortOrder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * @Author Lijx
 * @Date 2024-07-29 16:08
 */
@Service
public class SearchServiceImpl implements SearchService {

    @Autowired
    private RestHighLevelClient restHighLevelClient;
    @Autowired
    private HistorySearchService historySearchService;

    /**
     * 搜索文章
     * @param searchDto
     * @return
     */
    @Override
    public ResponseResult searchArticle(UserSearchDto searchDto) {

        //保存用户搜索的关键词到mongoDB中
        historySearchService.saveSearchWords(searchDto.getSearchWords(), ApThreadLocalUtil.getUserId());

        try {
            //指定查询索引库条件
            SearchRequest searchRequest = new SearchRequest("app_info_article");

            //1.1 组装bool查询条件
            BoolQueryBuilder boolQuery = QueryBuilders.boolQuery();
            boolQuery.must(QueryBuilders.multiMatchQuery(searchDto.getSearchWords(),"title","content"));
            boolQuery.filter(QueryBuilders.rangeQuery("publishTime").lte(searchDto.getMinBehotTime()));
            searchRequest.source().query(boolQuery);

            //1.2 组装分页条件
            searchRequest.source().from(searchDto.getFromIndex());
            searchRequest.source().size(searchDto.getPageSize());

            //1.3 组装排序
            searchRequest.source().sort("publishTime", SortOrder.DESC);

            //1.4 高亮显示
            searchRequest.source().highlighter(new HighlightBuilder()
                            .field("title")
                            .preTags("<font style='color: red; font-size: inherit;'>")
                            .postTags("</font>"));

            SearchResponse response = restHighLevelClient.search(searchRequest, RequestOptions.DEFAULT);

            //解析搜索结果
            SearchHit[] hits = response.getHits().getHits();

            //创建集合存储文章列表数据
            List<JSONObject> res = new ArrayList<>();

            for (SearchHit hit : hits) {
                String sourceAsString = hit.getSourceAsString();
                JSONObject jsonObject = JSONObject.parseObject(sourceAsString);

                //获取高亮显示字段
                Map<String, HighlightField> highlightFields = hit.getHighlightFields();
                if (highlightFields != null && highlightFields.size() > 0) {
                    //标题title高亮处理
                    String title = highlightFields.get("title").getFragments()[0].string();
                    jsonObject.put("h_title",title);
                }else {
                    //没有高亮则显示原标题
                    jsonObject.put("h_title",jsonObject.get("title"));
                }
                //添加文章到集合
                res.add(jsonObject);
            }

            return ResponseResult.okResult(res);
        } catch (IOException e) {
            e.printStackTrace();
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST);
        }

    }
}
